const express = require('express')
const pool = require('../pool')
const r = express.Router()
const jwt = require('jsonwebtoken')
const key = 'my key'

r.get('/verifyucode',(req,res,next)=>{
    let ucode = req.query.ucode
    let token = req.headers.authorition
    jwt.verify(token,key,(err,decoded)=>{
        if(err!=null)
        {
            res.send({msg:'token不合法请刷新重试'})
            return
        }
        console.log(token);
        console.log(ucode);
        pool.query('select * from hx_code where hxkey=? and hxvalue = ?;',[token,ucode],(err,result)=>{
            if(err){
                next(err)
                return
            }
            if(result.length == 0)
            {
                console.log(token);
                console.log('验证码是'+req.query.ucode);
                res.send({code:201,msg:'验证码错误'})
                return
            }
            res.send({code:200,msg:'验证码正确'})
        })
    })
   
})
r.get('/gettoken',(req,res)=>{
    let payload = {exp:Date.now()/1000+3600*24} //初始化token  1天过期
    let token = jwt.sign(payload,key)
    res.send({token:token})
})
const captcha = require('svg-captcha')
r.get('/verifytoken',(req,res,next)=>{
    let token = req.headers.authorition
    jwt.verify(token,key,(err,decoded)=>{
        if(err!=null)
        {
            res.send({msg:'token不合法请刷新重试'})
            return
        }
        let capt = captcha.create()
        pool.query('insert into hx_code values (?,?);',[token,capt.text.toLowerCase()],(err,result)=>{
            if(err){
                next(err)
                return
            }
        })
        res.send({code:200,msg:'验证码获取成功',ucode:capt.data})
    })

})


r.post('/admin',(req,res,next)=>{
    let obj = req.body
    pool.query(`select * from hx_admin where uname=? and upwd=md5(?);`,[obj.uname,obj.upwd],(err,result)=>{
        if(err){
            next(err)
            return
        }
        if(result.length==0)
        {
            res.send({code:201,msg:'登录失败'})
            return
        }
        res.send({code:200,msg:'登录成功',data:result})
    })
})

module.exports = r


